﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Windows.Forms;
using System.Collections;

namespace RuoTeng.Util
{
    class Http
    {

        static public string GetData(string url, System.Net.CookieContainer cookies)
        {
            return GetDataOverride(url, null, null, cookies,null);
        }

        static public string GetData(string url, System.Net.CookieContainer cookies,Encoding code)
        {
            return GetDataOverride(url, null, null, cookies, code);
        }

        static public string GetData(string url, string data, System.Net.CookieContainer cookies)
        {
            return GetDataOverride(url, data, null, cookies,null);
        }

        
      


        static public string GetData(string url, string data, System.Net.CookieContainer cookies,Encoding code)
        {
            return GetDataOverride(url, data, null, cookies, code);
        }

        static public string GetDataOverride(string url, HashMap<string, string> header, System.Net.CookieContainer cookies)
        {
            return GetDataOverride(url, null, header, cookies,null);
        }

        static public string GetDataOverride(string url, string data, HashMap<string, string> header, System.Net.CookieContainer cookies,System.Text.Encoding code)
        {
            string result = "";
            try
            {
                System.IO.Stream __Stream = GetStreamOverride(url, data, header, cookies);
                if (__Stream != null)
                {

                    System.IO.StreamReader __StreamReader=null;
                    if (code == null)
                    {
                         __StreamReader =new System.IO.StreamReader(__Stream, Encoding.Default);
                    }
                    else
                    {
                         __StreamReader = new System.IO.StreamReader(__Stream, code);
                    }
                   
                    result = __StreamReader.ReadToEnd();
                    __Stream.Close();
                }              
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return result;
        }
         

        static public System.IO.Stream GetStream(string url, System.Net.CookieContainer cookies)
        {
            return GetStreamOverride(url, null, null, cookies);
        }

        static public System.IO.Stream GetStream(string url,string data,System.Net.CookieContainer cookies)
        {
            return GetStreamOverride(url, data, null, cookies);
        }

        static public System.IO.Stream GetStreamOverride(string url, HashMap<string, string> header, System.Net.CookieContainer cookies)
        {
            return GetStreamOverride(url, null, header, cookies);
        }

        static public System.IO.Stream GetStreamOverride(string url, string data, HashMap<string, string> header, System.Net.CookieContainer cookies)
        {
            System.IO.Stream stream = null;
            try
            {
                System.Net.HttpWebResponse response = GetResponse(url, data, header, cookies);
                if (response != null)
                {
                    stream = response.GetResponseStream();
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return stream;
        }

        static public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受    
            return true;
        }

        static public System.Net.HttpWebResponse GetResponse(string url, string data, HashMap<string, string> header, System.Net.CookieContainer cookies)
        {
            System.Net.HttpWebRequest request = null;
            System.Net.HttpWebResponse response = null;
            try
            {

                request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                request.Timeout = 30000;
                request.AllowAutoRedirect = true;
                request.KeepAlive = true;

                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
                //------------------------------------------------------------------------------------------------------------
                request.CookieContainer = cookies;
                if (data != null && data != "")
                {
                    //request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                    request.ContentType = "application/x-www-form-urlencoded;";
                }
                if (header != null)
                {
                    foreach (System.Collections.Generic.KeyValuePair<string, string> pari in header)
                    {
                        switch (pari.Key.Trim().ToLower())
                        {
                            case "referer": request.Referer = pari.Value; break;
                            case "timeout": int __timeout = 10000; int.TryParse(pari.Value, out __timeout); request.Timeout = __timeout; break;
                            default: request.Headers.Add(pari.Key, pari.Value); break;
                        }
                    }
                }
                if (data != null && data != "")
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(data);
                    request.Method = "POST";
                    request.ContentLength = bytes.Length;
                    System.IO.Stream stream = request.GetRequestStream();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                }
                //------------------------------------------------------------------------------------------------------------
                response = (System.Net.HttpWebResponse)request.GetResponse();
                if (response != null)
                {
                    foreach (System.Net.Cookie cookie in response.Cookies)
                    {
                        if (!cookie.Domain.StartsWith("."))
                        {
                            cookie.Domain = cookie.Domain;
                            System.Net.Cookie _cookie = new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain);
                            if (cookies != null)
                            {
                                cookies.Add(_cookie);
                            }
                        }
                    }

                }
            }

            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }


            return response;
        }

        /// <summary>
        /// 迭代所以cookie
        /// </summary>
        /// <param name="cc"></param>
        /// <returns></returns>

        public List<Cookie> GetAllCookies(CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();
            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
             System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                   System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                   | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies)
                    {
                        lstCookies.Add(c);
                        if (c.Name == "skey")
                        {
                            //this.skey = c.Value;
                        }
                    }
            }

            return lstCookies;
        }



        /// <summary>
        /// 获取cookie指定键值
        /// </summary>
        /// <param name="cc"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetAllCookies(CookieContainer cc, string name)
        {

            string str = "";
            List<Cookie> lstCookies = new List<Cookie>();
            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
             System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                   System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                   | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies)
                    {
                        lstCookies.Add(c);
                        if (c.Name == name)
                        {
                            str = c.Value;
                        }
                    }
            }

            return str;
        }


        /// <summary>
        /// 获取验证码图片
        /// </summary>
        /// <returns>图片对象</returns>
        public System.Drawing.Image GetVerifyCodeImage(string vctype)
        {
           // string url = "http://captcha.qq.com/getimage?aid=" + this._Params["aid"] + "&r=0.15603948633583958&uin=" + this._Params["u"] + "&vc_type=" + vctype;
          return System.Drawing.Image.FromStream( Http.GetStream("", null));
        }


        public static string UrlEncode(string str, Encoding code)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = null;
            if (code == null)
            {
                byStr = System.Text.Encoding.Default.GetBytes(str);
            }
            else
            {
                byStr = code.GetBytes(str);
            }
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return (sb.ToString().ToUpper());
        }
    }
}
